package com.lagou.rpc.provider.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class ZkRegister {

    public static void restister(){

        CuratorFramework curatorClient = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(1000, 3));
        curatorClient.start();

        try {
            Stat stat = curatorClient.checkExists().forPath("/server");
            if(Objects.isNull(stat)){
                curatorClient.create().withMode(CreateMode.PERSISTENT).forPath("/server");
            }else {
                String serverHost = InetAddress.getLocalHost().getHostName();
                curatorClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/server/"+serverHost,serverHost.getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }


    }
}
